package com.fin.zw.intelligentbot.controller.api;


import com.fin.zw.intelligentbot.annotation.CurrentUser;
import com.fin.zw.intelligentbot.entity.DialTask;
import com.fin.zw.intelligentbot.entity.RobotInfo;
import com.fin.zw.intelligentbot.entity.TaskCustomer;
import com.fin.zw.intelligentbot.model.ResulteWraper;
import com.fin.zw.intelligentbot.model.base.Customer;
import com.fin.zw.intelligentbot.model.base.Robot;
import com.fin.zw.intelligentbot.model.base.Task;
import com.fin.zw.intelligentbot.model.request.DialTaskParamRequest;
import com.fin.zw.intelligentbot.model.request.DialTaskRequest;
import com.fin.zw.intelligentbot.model.response.DialTaskResponse;
import com.fin.zw.intelligentbot.model.session.SessionModel;
import com.fin.zw.intelligentbot.service.DialTaskService;
import com.fin.zw.intelligentbot.service.SocketService;
import com.fin.zw.intelligentbot.service.UploadFileService;
import com.fin.zw.intelligentbot.util.FileUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/task")
@Api(value = "任务管理", description = "任务管理")
public class TaskControler {

    @Autowired
    private DialTaskService dialTaskService;

    @Autowired
    private SocketService socketService;

    @Autowired
    private UploadFileService uploadFileService;

    @GetMapping("/fetch")
    @ApiOperation(value = "查询任务", notes = "查询任务")
    public ResponseEntity<ResulteWraper> fetch(DialTaskParamRequest condition, @ApiIgnore @CurrentUser SessionModel sessionModel) {
        ResulteWraper wraper = new ResulteWraper();
        List<Task> tasks = new ArrayList<>();
        Map<DialTask, List<TaskCustomer>> taskGroup = dialTaskService.fetch(condition, sessionModel);

        taskGroup.forEach((tg, tcs) -> {
            Task task = new Task();
            BeanUtils.copyProperties(tg, task);
            task.setStatus(tg.getStatus().toString());
            List<Customer> customers = new ArrayList<>();
            tcs.forEach(c -> {
                Customer customer = new Customer();
                BeanUtils.copyProperties(c, customer);
                if (Objects.nonNull(c.getAttitude())) {
                    customer.setAttitude(c.getAttitude().getCode());
                    customer.setAttitudeName(c.getAttitude().getName());
                }
                customer.setStatus(c.getStatus().toString());
                customer.setSex(c.getSex().toString());
                if (Objects.nonNull(c.getDialogContent()))
                    customer.setContentFile(c.getDialogContent());
                if (Objects.nonNull(c.getDialogRecord()))
                    customer.setRecordFile(c.getDialogRecord());
                if (Objects.nonNull(c.getRobotInfo())) {
                    Robot robot = new Robot();
                    robot.setId(c.getRobotInfo().getId());
                    robot.setName(c.getRobotInfo().getName());
                    robot.setCode(c.getRobotInfo().getCode());
                    customer.setRobot(robot);
                }
//                    customer.setRobotName(c.getRobotInfo().getName());
                customers.add(customer);
            });
            task.setCustomers(customers);
            tasks.add(task);
        });

        wraper.setData(tasks);
        return ResponseEntity.ok().body(wraper);
    }


    @GetMapping("/fetchTask")
    @ApiOperation(value = "查询任务",notes = "查询任务")
    public ResponseEntity<ResulteWraper> fetchTask(DialTaskParamRequest condition, @ApiIgnore @CurrentUser SessionModel sessionModel) throws Exception {
        ResulteWraper wraper = new ResulteWraper();
        List<DialTaskResponse> dialTaskResponses = dialTaskService.fetchApi(condition, sessionModel);
        List<Task> tasks = dialTaskResponses.stream().map(dialTask -> {
            Task task = new Task();
            BeanUtils.copyProperties(dialTask, task, "customers");
            task.setStatus(dialTask.getStatus().toString());
            if (dialTask.getRobots() != null && !dialTask.getRobots().isEmpty()) {
                Set<Robot> robots = new HashSet<>();
                for (RobotInfo robotInfo : dialTask.getRobots()) {
                    Robot robot = new Robot();
                    BeanUtils.copyProperties(robotInfo, robot);
                    robots.add(robot);
                }
                task.setRobotSet(robots);
            }

            return task;
        }).collect(Collectors.toList());
        wraper.setData(tasks);
        return ResponseEntity.ok().body(wraper);
    }

    @PostMapping("/add")
    @ApiOperation(value = "创建任务信息",notes = "创建任务信息")
    public ResponseEntity<ResulteWraper> add(@RequestBody DialTaskRequest request,
                                                @ApiIgnore @CurrentUser SessionModel sessionModel) throws Exception {
        ResulteWraper wraper = new ResulteWraper();
        DialTask task = dialTaskService.createDialTask(request, sessionModel, wraper);
        Map<String,Object> map = new HashMap<>();
        map.put("id",task.getId());
        map.put("name",task.getName());
        map.put("parentId", task.getParentId());
        map.put("initId", task.getInitId());
        map.put("scene",request.getScene());
        map.put("robots",request.getRobots());
        map.put("customers",null);
        wraper.setData(map);
        return ResponseEntity.ok().body(wraper);
    }


    @PostMapping("/addTask")
    @ApiOperation(value = "创建任务信息",notes = "创建任务信息")
    public ResponseEntity<ResulteWraper> addTask(@RequestBody DialTaskRequest request,
                                             @ApiIgnore @CurrentUser SessionModel sessionModel) throws Exception {
        ResulteWraper resulteWraper = new ResulteWraper();
        dialTaskService.createDialTask(request, sessionModel);
        return ResponseEntity.ok().body(resulteWraper);
    }

    @GetMapping("/cancel")
    @ApiOperation(value = "任务取消", notes = "任务取消")
    public ResponseEntity<String> cancel(@RequestParam("taskId") String taskId) {
        socketService.cancelTask(taskId);
        return ResponseEntity.ok().body("操作成功");
    }

    @GetMapping("/fetchContext")
    @ApiOperation(value = "获取对话内容", notes = "获取对话内容")
    public ResponseEntity<String> fetchContext(@RequestParam(value = "fileName", required = false) String fileName,
                                               @RequestParam(value = "fileId", required = false) String fileId) throws Exception {

        if (StringUtils.isNotEmpty(fileId))
            return ResponseEntity.ok().body(FileUtil.readFile(uploadFileService.findOneFileById(fileId)));
        else if (StringUtils.isNotEmpty(fileName))
            return ResponseEntity.ok().body(FileUtil.readFile(uploadFileService.findOneFileByName(fileName)));

        return ResponseEntity.ok().body("");
    }
}
